package tw.com.book.componet;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import tw.com.book.BookApplication;
import tw.com.book.domain.Coloumn;
import tw.com.book.domain.DBDomain;
import tw.com.book.domain.Table;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.util.Log;

public class VoUtils {

	private static final String TAG = VoUtils.class.getCanonicalName();

	public static List<TableContent> loadAllDomain(Context ct) {
		final List<TableContent> tables = new ArrayList<TableContent>();
		try {
			Properties pro = new Properties();
			pro.load(ct.getAssets().open("db.properties"));

			for (Object key : pro.keySet()) {
				final String claaPath = (String) pro.get(key);
				final Class pClasss = Class.forName(claaPath);
				final TableContent tmp = getTableContent(pClasss);
				tables.add(tmp);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return tables;
	}

	public static <T extends DBHelper> TableContent getTableContent(
			Class<T> domain) {

		final TableContent content = new TableContent();
		// final Table table = domain.getAnnotation(Table.class);

		content.setTable(domain.getSimpleName());

		final Field[] fs = domain.getDeclaredFields();
		for (Field f : fs) {

			// final Class<?> pClass = f.getName();
			final String name = f.getName();

			final Coloumn column = f.getAnnotation(Coloumn.class);

			if (column == null) {
				continue;
			}

			final PairValue value = new PairValue();
			value.setFielName(name);// type之欄位名稱
			value.setFileTableName(column.name());// table 欄位名稱

			switch (column.type()) {
			case JUST_COlUMN:
				value.setPk(false);// isPk
				break;

			case PK:
				value.setPk(true);
				break;

			default:
				break;
			}
			content.getPairs().add(value);

		}

		return content;
		// content.getPairs()

	}

	public static TableContent getApp(Class pClass, Context ct)
			throws IssueBussinessException {
		final BookApplication app = (BookApplication) ct
				.getApplicationContext();
		final TableContent tabContent = app.getTable(pClass.getSimpleName());
		return tabContent;

	}

	public static ContentValues getContentValues(DBDomain domain, Context ct)
			throws IssueBussinessException {
		try {

			final BookApplication app = (BookApplication) ct
					.getApplicationContext();

			final TableContent tabContent = app.getTable(domain.getClass()
					.getSimpleName());

			final ContentValues map = new ContentValues();

			for (PairValue value : tabContent.getPairs()) {

				final Field f = domain.getClass().getDeclaredField(
						value.getFielName());
				f.setAccessible(true);

				map.put(value.getFileTableName(), (String) f.get(domain));

				f.setAccessible(false);

			}
			return map;

		} catch (Exception e) {
			Log.v(TAG, e.toString());
			throw new IssueBussinessException(Msg.E003);
		}

	}

}
